<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Image;
use Illuminate\Http\File;

class ImageController extends BaseController
{
    public function store(Request $request)
    {
        /*$streamData = file_get_contents('php://input');

        $extension = 'png';
        $filename = md5(time().str_random(16)).'.'.$extension;
        $dir = date('Ymd');

        $path = public_path('storage/'.$dir);

        if(!is_dir($path))
        {
            Storage::makeDirectory('public/'.$dir, 0777, true, true);
        }

        $receiveFile = $path.'/'.$filename;  //最终落地的文件目录和文件名
        $ret = file_put_contents($receiveFile, $streamData, true);

        if($ret)
        {
            $disk = Storage::disk('oss');
            //上传到阿里云oss
            $disk->putFileAs($dir, new File($receiveFile), $filename);
            $url = $disk->getUrl($dir.'/'.$filename);
            return ok([
                'url' => $url,
            ]);
        }

        return $this->err(1,200,'','上传失败');*/
        $file        = $request->file('file');
        $thumb       = (int) $request->get('thumb',0);
        $thumb_width = (int) $request->get('thumb_width',400);


        $disk = Storage::disk('oss');
        $extension = $file->getClientOriginalExtension();
        $filename = md5(time().str_random(16)).'.'.$extension;
        $dir = date('Ymd');

        //上传到阿里云oss
        $disk->putFileAs($dir, $file, $filename);
        $url = $disk->getUrl($dir.'/'.$filename);
        $thumb_url = '';
        if($thumb)
        {
            //临时保存到本地存储
            $local_path = $file->storeAs($dir, $filename,'public');
            Image::make('storage/'.$local_path)
                ->resize($thumb_width, null, function($constraint) {
                    $constraint->aspectRatio();
                    $constraint->upsize();
                })->save();

            $thumb_filename = $filename."_{$thumb_width}".'.'.$extension;

            $disk->putFileAs($dir, new File(public_path('storage/'.$local_path)), $thumb_filename);
            $thumb_url = $disk->getUrl($dir.'/'.$thumb_filename);
            Storage::disk('public')->delete($local_path);
        }


        return ok([
            'url'       => $url,
            'thumb_url' => $thumb_url
        ]);
    }
}
